package com.bocloud.cmp.driver.providers.os;

import java.util.Date;
import java.util.List;

import org.openstack4j.model.common.ActionResponse;
import org.openstack4j.model.compute.SecGroupExtension;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.bocloud.cmp.driver.providers.SecurityGroupDriver;
import com.bocloud.cmp.model.SecurityGroupModel;
import com.bocloud.common.model.BsmResult;
import com.google.common.collect.Lists;

public class OSSecurityGroupDriver extends OSDriver implements SecurityGroupDriver {

	private static Logger logger = LoggerFactory.getLogger(OSSecurityGroupDriver.class);

	/**
	 * 
	 */
	public OSSecurityGroupDriver() {
		super();
	}

	public OSSecurityGroupDriver(String endpoint, String username, String password, String tenant, String domain,
			String project, Version version) {
		super(endpoint, username, password, tenant, domain, project, version);
	}

	@Override
	public BsmResult list() {
		List<SecurityGroupModel> models = Lists.newArrayList();
		if (!this.accessable()) {
			logger.error(this.getError());
			return new BsmResult(false, this.getError());
		}
		List<? extends SecGroupExtension> sgroups = this.getClient().compute().securityGroups().list();
		if (null != sgroups) {
			for (SecGroupExtension sgroup : sgroups) {
				models.add(convert(sgroup));
			}
		}
		return new BsmResult(true, models, "success");
	}

	@Override
	public BsmResult create(SecurityGroupModel group) {
		if (!this.accessable()) {
			logger.error(this.getError());
			return new BsmResult(false, this.getError());
		}
		SecGroupExtension result = this.getClient().compute().securityGroups().create(group.getName(),
				group.getRemark());
		group.setGmtCreate(new Date());
		group.setUuid(result.getId());
		return new BsmResult(true, group, "succsss");
	}

	@Override
	public BsmResult remove(String sgId) {
		if (!this.accessable()) {
			logger.error(this.getError());
			return new BsmResult(false, this.getError());
		}
		ActionResponse response = this.getClient().compute().securityGroups().delete(sgId);
		if (response.isSuccess()) {
			return new BsmResult(true, "删除成功！");
		} else {
			logger.error("remove securitygroup [{}] failed :{}", sgId, response.getFault());
			return new BsmResult(false, "删除失败！");
		}
	}

	@Override
	public BsmResult detail(String sgId) {
		if (!this.accessable()) {
			logger.error(this.getError());
			return new BsmResult(false, this.getError());
		}
		SecGroupExtension sgroup = this.getClient().compute().securityGroups().get(sgId);
		if (null == sgroup) {
			return new BsmResult(false, "安全组不存在！");
		} else {
			return new BsmResult(true, convert(sgroup), "success");
		}
	}

	private SecurityGroupModel convert(SecGroupExtension sgroup) {
		if (null == sgroup) {
			return null;
		}
		SecurityGroupModel model = new SecurityGroupModel(sgroup.getId(), sgroup.getName(), sgroup.getDescription(),
				new Date(), null);
		return model;
	}
}
